package com.itcam.phaseiii.thread_;

/**
 * Author:Cammy.Wu
 * Date:2024-05-11
 * Description:
 */

/**
 * 同步方法<p>
 * ⚪在方法的返回值类型前面加synchrinized关键字<p>
 * public synchronized void method(){<p>
 * <p>
 * }
 * <p>
 * 同步方法的锁对象：<p>
 * 1.非静态的方法：this<p>
 * 2.静态的方法：类的字节码对象<p>
 */

public class ThreadTest04 {
    public static void main(String[] args) {
        TicketTask4 task = new TicketTask4();

        Thread t1 = new Thread(task, "窗口1");
        Thread t2 = new Thread(task, "窗口2");
        Thread t3 = new Thread(task, "窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class TicketTask4 implements Runnable {
    private int ticket = 100;

    @Override
    public void run() {

        while (true) {
            String name = Thread.currentThread().getName();
            if ("窗口1".equals(name)) {
                if (method()) {
                    break;
                }
            } else if ("窗口2".equals(name)){
                synchronized (this) {
                    if (ticket == 0) {
                        break;
                    }
                    System.out.println(Thread.currentThread().getName() + "卖出了第" + ticket + "张票");
                    ticket--;
                }
            }
        }
    }

    private synchronized boolean method() {
        if (ticket == 0) {
            return true;
        }
        System.out.println(Thread.currentThread().getName() + "卖出了第" + ticket + "张票");
        ticket--;
        return false;
    }


}